//角色管理 
Ext.define('Logisticext.module.RoleManagement', {
    extend: 'Ext.Panel',
    layout: 'border',
    initComponent: function() {
        var _this = this;
        var grid;
        var keywordsField = Ext.create('Ext.form.field.Text', {
            // 这里打算使用 hibernate serach 几个列加全文搜索，不针对具体字段搜索
            name: 'keywords',
            xtype: 'textfield'
        });
        // 工具栏
        this.tbar = [{
                text: '添加',
                disabled: _this.perms['ADD'] ? false : true,
                handler: function() {
                    _this.showAddWindow();
                }
            }, {
                text: '编辑',
                disabled: _this.perms['EDIT'] ? false : true,
                handler: function() {
                    if (grid.getSelectionModel( ).hasSelection( )) {
                        var record = grid.getSelectionModel( ).getSelection( )[0];
                        _this.showEditWindow(record);
                    }
                }
            }, {
                text: '删除',
                disabled: _this.perms['REMOVE'] ? false : true,
                handler: function() {
                    if (grid.getSelectionModel( ).hasSelection( )) {
                        var record = grid.getSelectionModel( ).getSelection( )[0];
                        Ext.Ajax.request({
                            url: F.url("/management/role/remove"),
                            params:{
                                roleId:record.get('roleId')
                            },
                            success: function(response) {
                                var text = response.responseText;
                                var result = Ext.JSON.decode(text);
                                if (result.success) {
                                    grid.getStore().reload();
                                } else {
                                    Ext.Msg.alert("删除失败", result.msg || "请重试");
                                }
                            },
                            failure: function(response, opts) {
                               Ext.Msg.alert("删除失败", "内部错误");
                            }
                        });
                    }
                }
            }, '->', '-', keywordsField, {
                text: '搜索',
                pressed: true,
                handler: function() {
                    grid.getStore().load({
                        params: {
                            keywords: keywordsField.getValue()
                        }
                    });
                }
            }];
        var fields = ['roleId', 'roleName', {name: 'roleExplain', type: 'string'}];
        var columns = [{xtype: 'rownumberer'}, {
                text: '主键',
                dataIndex: 'roleId'
            }, {
                text: '名称',
                dataIndex: 'roleName'
            }, {
                text: '说明',
                dataIndex: 'roleExplain',
                flex: 1
            }];
        var store = Ext.create('Ext.data.Store', {
            storeId: 'roleStore',
            pageSize: 50,
            proxy: {
                type: 'ajax',
                url: F.url('/management/role/list'),
                method: 'post',
                extraParams: {
                },
                reader: {
                    type: 'json',
                    root: 'roleList.list',
                    idProperty: 'roleId',
                    messageProperty: "msg"
                }
            },
            //alternatively, a Ext.data.Model name can be given (see Ext.data.Store for an example)
            fields: fields
        });
        // 列表
        grid = Ext.create('Ext.grid.Panel', {
            itemId: 'grid',
            dockedItems: [{
                    xtype: 'pagingtoolbar',
                    store: store, // same store GridPanel is using
                    dock: 'bottom',
                    displayInfo: true
                }],
            region: 'center',
            store: store,
            columns: columns,
            listeners: {
                render: function() {
                    store.load();
                }
            }
        });
        _this.items = [grid];
        this.callParent();
    },
    //弹出添加窗口
    showAddWindow: function() {
        var _this = this;
        Ext.create('Logisticext.module.RoleManagement.FormWindow', {
            title: '创建角色',
            formUrl: F.url('/management/role/add'),
            submitSuccessCallback: function(win) {
                win.close();
                _this.getComponent('grid').getStore().reload();
            }
        }).show();
    },
    //弹出修改窗口
    showEditWindow: function(rec) {
        var _this = this;
        Ext.create('Logisticext.module.RoleManagement.FormWindow', {
            title: '编辑角色和权限',
            formUrl: F.url('/management/role/update'),
            role: rec,
            submitSuccessCallback: function(win) {
                win.close();
                _this.getComponent('grid').getStore().reload();
            }
        }).show();
    }
});
//角色Form表单窗口
Ext.define('Logisticext.module.RoleManagement.FormWindow', {
    extend: 'Ext.window.Window',
    height: 600,
    width: 800,
    layout: 'border',
    modal: true,
    initComponent: function() {
        var win = this;
        Ext.apply(this, {
            buttons: [{
                    text: '确认',
                    scope: this,
                    handler: function() {
                        //收集角色,与表单一起提交
                        var records = win.getComponent('permTree').getView().getChecked();
                        var perms = [];
                        Ext.Array.each(records, function(rec) {
                            if (rec.raw.value) {
                                perms.push(rec.raw.value);
                            }
                        });
                        win.getComponent('form').submit({
                            clientValidation: true,
                            params: {
                                perms: perms
                            },
                            success: function(form, action) {
                                if (win.submitSuccessCallback) {
                                    win.submitSuccessCallback(win);
                                } else {
                                    win.close();
                                }
                            },
                            failure: function(form, action) {
                                if (win.submitFailureCallback) {
                                    win.submitFailureCallback(win);
                                } else {
                                    switch (action.failureType) {
                                        case Ext.form.action.Action.CLIENT_INVALID:
                                            Ext.Msg.alert('失败', '请检查输入的内容是否完整并且无误');
                                            break;
                                        case Ext.form.action.Action.CONNECT_FAILURE:
                                            Ext.Msg.alert('失败', '请求超时，请检查网络是否正常');
                                            break;
                                        case Ext.form.action.Action.SERVER_INVALID:
                                            Ext.Msg.alert('失败', action.result.msg);
                                    }
                                }
                            }
                        });
                    }
                }]
        });
        var form = Ext.create("Ext.form.Panel", {
            itemId: 'form',
            region: 'center',
            bodyPadding: 5,
            url: this.formUrl,
            layout: 'anchor',
            defaults: {
                anchor: '100%'
            },
            // The fields
            defaultType: 'textfield',
            items: [{
                    xtype: 'hiddenfield',
                    name: 'roleId'
                }, {
                    fieldLabel: '角色名称',
                    name: 'roleName',
                    allowBlank: false,
                    emptyText: '请输入角色名称',
                    blankText: '角色名称不能为空'
                }, {
                    fieldLabel: '说明',
                    name: 'roleExplain',
                    allowBlank: true,
                    xtype: 'textareafield',
                    grow: false
                }]
        });
        var tree = Ext.create('Logisticext.common.CheckableTreePanel', {
            title: '权限',
            region: 'west',
            width: 300,
            height: 150,
            itemId: 'permTree',
            store: new Ext.data.TreeStore({
                proxy: {
                    type: 'ajax',
                    url: F.url('/management/role/perm_treenodes'),
                    extraParams: {
                        roleId: this.role ? this.role.get('roleId') : null
                    }
                }
            })
        });
        this.items = [tree, form];
        this.callParent();
        if (this.role) {
            form.loadRecord(this.role);
        }
    }
});